package com.unismc.uview.service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.unismc.uview.vo.WeatherResponse;

@Service
public class WeatherDataServiceImpl implements WeatherDataService {
	private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";
	private static final long TIME_OUT = 100L;
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public WeatherResponse getDataByCityId(String cityId) {
		String uri = WEATHER_URI + "citykey=" + cityId;
		return this.getWeahter(uri);
	}

	@Override
	public WeatherResponse getDataByCityName(String cityName) {
		String uri = WEATHER_URI + "city=" + cityName;
		return this.getWeahter(uri);
	}
	
	private void setCache(String key, String value) {
		ValueOperations<String, String> ops = redisTemplate.opsForValue();
		ops.set(key, value, TIME_OUT, TimeUnit.SECONDS);
	}

	private String getFromCache(String key) {
		ValueOperations<String, String> ops = redisTemplate.opsForValue();
		return ops.get(key);
	}

	private String getFromRemote(String key) {
		String strBody = null;
		ResponseEntity<String> respString = restTemplate.getForEntity(key, String.class);

		if (respString.getStatusCodeValue() == 200) {
			strBody = respString.getBody();
			setCache(key, strBody);
		}		
		
		return strBody;
	}

	private WeatherResponse getWeahter(String uri) {
		String key = uri;
		String strBody = null;
		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;

		// 先查缓存，缓存有的取缓存中的数据,缓存没有，再调用服务接口来获取
		strBody = redisTemplate.hasKey(key) ? getFromCache(key) : getFromRemote(key);
		try {
			resp = mapper.readValue(strBody, WeatherResponse.class);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return resp;
	}

	@Override
	public void syncDataByCityId(String cityId) {
		String uri = WEATHER_URI + "citykey=" + cityId;
		getFromRemote(uri);
	}
}
